<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="/css/weui.min.css" />
        <link rel="stylesheet" href="/css/bootstrap.min.css" />
        <title>上传PDF</title>
        <style>
            .upload-btn {
                position: relative;
            }
            .list-group-item {
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
            .list-group-item h1 {
                padding: 0;
                margin: 0;
                font-size: 16px;
            }
            .list-group-item h2 {
                padding: 0;
                margin-top: 5px;
                font-size: 12px;
                color: #9c9c9c;
            }
            /* .list-group-item .qrcode-btn{
                height: 40px;
            } */
            .list-group p{
                margin:0;
                padding:0;
            }
            .list-group .left{
                cursor: pointer;
            }
            .right .btn {
                height: 40px;
            }
            .center p,.left-name p{
                font-size: 14px;
                color: #9c9c9c;
            }
            .modal .content {
                margin: auto;
            }
            .modal .btn {
                display: flex;
                justify-content: space-evenly;
            }
            .uploaded {
                background-color: rgba(65, 195, 33, 0.1) !important;
            }
            .pagination {
                margin-top: 50px;
            }
            .page-item a {
                cursor: pointer;
            }
            .more-ctrl{
                display: flex;
                flex-direction: row;
            }
            @media (max-width: 575.98px) { 
                .more-ctrl{
                    flex-direction: column;   
                }
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div id="upload"></div>
            <div>
                <!-- <ul class="weui-uploader__files" id="uploaderFiles"></ul> -->
                <button
                    id="addCodeBtn"
                    type="button"
                    data-toggle="modal"
                    data-target="#addFileModal"
                    class="btn btn-outline-info qrcode-btn"
                >
                    生成二维码
                </button>
            </div>
            <div>
                <ul class="list-group"></ul>
                <!-- Pagination -->
                <nav>
                    <ul
                        id="pagination"
                        class="pagination justify-content-center"
                    >
                        <!-- Pagination items go here -->
                    </ul>
                </nav>
            </div>
            <!-- Modal -->
            <div class="modal fade"
                id="addFileModal"
                data-backdrop="static"
                tabindex="-1"
                aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">添加文件</h5>
                            <button
                                type="button"
                                class="close"
                                data-dismiss="modal"
                                aria-label="Close"
                            >
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <form action="#" class="add-form" novalidate>
                              <div class="form-group">
                                <label for="fileName">输入文件验证码：</label>
                                <input type="text" class="form-control" id="fileName" required>
                                <div class="invalid-feedback">
                                    <span id="fileNameInfo">验证码不能为空</span>
                                </div>
                                <small class="form-text text-muted">验证码会作为此文件名称，并要求唯一性。</small>
                                
                              </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button
                                type="button"
                                class="btn btn-secondary"
                                data-dismiss="modal"
                            >
                                关闭
                            </button>
                            <button id="addBtn" type="button" class="btn btn-primary">
                                保存
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal fade"
            id="updateWriteNameModal"
            data-backdrop="static"
            tabindex="-1"
            aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">修改姓名</h5>
                            <button
                                type="button"
                                class="close"
                                data-dismiss="modal"
                                aria-label="Close"
                            >
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <form action="#" class="writeName-form" novalidate>
                            <div class="form-group">
                                <label for="writeName">输入姓名：</label>
                                <input type="text" class="form-control" id="writeName" required>
                                <div class="invalid-feedback">
                                    <span id="writeNameInfo">姓名不能为空</span>
                                </div>
                                
                            </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button
                                type="button"
                                class="btn btn-secondary"
                                data-dismiss="modal"
                            >
                                关闭
                            </button>
                            <button id="updateWriteNameBtn" type="button" class="btn btn-primary">
                                保存
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <div
                class="modal fade"
                id="qrcodeModal"
                data-backdrop="static"
                tabindex="-1"
                aria-hidden="true"
            >
                
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-body content">
                            <div id="qrcode"></div>
                            <div class="btn">
                                <button
                                    id="down-btn"
                                    type="button"
                                    class="btn btn-primary"
                                >
                                    下载
                                </button>
                                <button
                                    type="button"
                                    class="btn btn-secondary"
                                    data-dismiss="modal"
                                >
                                    关闭
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <script src="/js/jquery-3.0.0.slim.min.js"></script>
        <script src="/js/bootstrap.min.js"></script>
        <script src="/js/weui.min.js"></script>
        <script src="/js/axios.min.js"></script>
        <!-- <script src="/js/jquery.qrcode.min.js"></script> -->
        <script src="/js/awesome-qr.js"></script>
        <script>
            /* 文件自动上传 */
            var uploadCount = 0,
                uploadList = [];
            var uploadCountDom = document.getElementById("uploadCount");
            let currentUploadId = "";
            let page = {};
            let updateId = "";
            let updateWriteName = "";
            // $("#down-btn").click(function(){
            //     console.log($("#qrcode img").attr("src"))
            //     window.location = $("#qrcode img").attr("src");
            // });

            function generateQRCode(text) {
                // qrcode.clear();
                // console.log(qrcode);
                // qrcode._oQRCode.typeNumber = 10;
                // qrcode.makeCode(text);
                // $("#qrcode").qrcode({text: text,typeNumber:10});
                new AwesomeQR.AwesomeQR({
                    text,
                    size: 256,
                    version: 10,
                    maskPattern: 3,
                    margin: 0,
                    correctLevel: AwesomeQR.QRErrorCorrectLevel.Q,
                })
                    .draw()
                    .then((dataURL) => {
                        $("#qrcode").html("<img src='" + dataURL + "'>");
                    });
            }
            function downQRCode(filename) {
                //找到需要转换的canvas
                // let data = $("#qrcode")
                //     .children()[0]
                //     .toDataURL()
                //     .replace("image/png", "image/octet-stream;"); //获取二维码值，并修改响应头部。
                let data = $("#qrcode").children()[0].src;
                let saveLink = document.createElement("a");
                saveLink.href = data;
                saveLink.download = filename;
                saveLink.click();
                // document.removeChild(saveLink);
            }
            async function getList(currentPage = 1) {
                let res = await axios({
                    method: "get",
                    url: "/files",
                    params: {
                        current: currentPage,
                        pageSize: 10,
                    },
                });
                page = res.data;
                renderPagination();
                let files = res.data.rows;

                let filesContent = "";
                files.forEach((item) => {
                    filesContent += `<li class="list-group-item ${
                        item.url ? "uploaded" : ""
                    }">
                        <div class="left" data-id="${item.id}">
                            <h1>${item.title}</h1>
                            <h2>创建时间：${item.createTime}</h2>
                        </div>
                        <div class="left-name">
                            <p>姓名：<span>${item.writeName || ''}</span></p>
                        </div>
                        <div class="center">
                            <p>${item.url ? "" : "未上传"}</p>
                        </div>
                       
                        <div class="right more-ctrl">
                            
                        <button  type="button" class="btn btn-outline-info text-nowrap qrcode-btn" data-url="${
                            item.forwardUrl
                        }" >查看二维码</button>
                        <button id="${
                            "upload-" + item.id
                        }" type="button" class="btn btn-outline-info upload-btn">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-upload" viewBox="0 0 16 16">
                            <path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"></path>
                            <path d="M7.646 1.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 2.707V11.5a.5.5 0 0 1-1 0V2.707L5.354 4.854a.5.5 0 1 1-.708-.708l3-3z"></path>
                            </svg>
                            上传
                            <input
                            id="${"uploaderInput-" + item.id}"
                            class="weui-uploader__input"
                            type="file"
                            accept="application/pdf"
                        />
                          </button>
                          <button  type="button" class="btn btn-outline-info text-nowrap download-btn" data-url="${
                            item.url ? item.url : ''
                          }" >下载</button>
                          <button  type="button" class="btn btn-outline-danger delete-btn" data-id="${
                              item.id
                          }" >删除</button>
                        </div>
                    </li>`;
                });
                $(".list-group").html(filesContent);
                $(".list-group .left").click((e) => {
                    updateId = e.currentTarget.dataset.id;
                    updateWriteName = $(e.target).parents(".list-group-item").find(".left-name span").text();
                    $("#writeName").val(updateWriteName);
                    $("#updateWriteNameModal").modal("show");
                });
                $(".list-group .qrcode-btn").click((e) => {
                    generateQRCode(e.target.dataset.url);
                    $("#qrcodeModal").modal("show");
                });
                $(".list-group .download-btn").click((e) => {
                    if(e.target.dataset.url){
                        // window.open(e.target.dataset.url);
                        
                        axios({
                            method: 'get',
                            url: e.target.dataset.url,
                            responseType: 'blob',
                            
                        }).then((res) => {
                            let fileName = "保存.pdf";
                            let filestream = "";
                            const blob = new Blob([res.data]);
                            const a = document.createElement('a');
                            const href = window.URL.createObjectURL(blob); // 创建下载连接
                            a.href = href;
                            a.download = decodeURI(fileName );
                            document.body.appendChild(a);
                            a.click();
                            document.body.removeChild(a); // 下载完移除元素
                            window.URL.revokeObjectURL(href); // 释放掉blob对象
                        });
                    }
                    
                });
                $(".list-group .delete-btn").click((e) => {
                    let id = e.target.dataset.id;
                    console.log("id", e.target.dataset.id);
                    weui.dialog({
                        title: "警告",
                        content: "是否删除当前文件？",
                        className: "custom-classname",
                        buttons: [
                            {
                                label: "取消",
                                type: "default",
                            },
                            {
                                label: "确定",
                                type: "primary",
                                onClick: async function () {
                                    await axios({
                                        method: "delete",
                                        url: "/files/" + id,
                                    });
                                    getList();
                                },
                            },
                        ],
                    });
                });
                files.forEach((item) => {
                    weui.uploader("#upload-" + item.id, {
                        url: "/upload",
                        auto: true,
                        type: "file",
                        fileVal: "file",
                        compress: false,
                        onBeforeQueued: function (files) {
                            console.log(this.type);
                            if (["application/pdf"].indexOf(this.type) < 0) {
                                weui.alert("请PDF文件");
                                return false;
                            }
                            if (this.size > 10 * 1024 * 1024) {
                                weui.alert("请上传不超过10M的文件");
                                return false;
                            }
                            if (files.length > 1) {
                                // 防止一下子选中过多文件
                                weui.alert("1次最多只能上传一个文档");
                                return false;
                            }
                            // ++uploadCount;
                            // uploadCountDom.innerHTML = uploadCount;
                        },

                        onBeforeSend: function (data, headers) {
                            console.log("onBeforeSend", data);
                            $.extend(data, { id: currentUploadId }); // 可以扩展此对象来控制上传参数
                            // $.extend(headers, { Origin: 'http://127.0.0.1' }); // 可以扩展此对象来控制上传头部
                            // return false; // 阻止文件上传
                        },
                        onSuccess: async function (ret) {
                            if (!ret.filename) {
                                // console.log("上传失败，请检查网络情况", +err);
                                weui.alert("上传失败，请检查网络情况");
                                return;
                            }
                            let res = await axios({
                                method: "put",
                                url: "/files/updateUrl/" + currentUploadId,
                                data: {
                                    url: ret.filename,
                                },
                            });
                            getList(page.current);
                            weui.toast("上传成功", 3000);
                        },
                        onError: function (err) {
                            // console.log("上传失败，请检查网络情况", +err);
                            weui.alert("上传失败，请检查网络情况");
                        },
                    });
                    $("#upload-" + item.id).click(() => {
                        currentUploadId = item.id;
                    });
                });
            }

            // Function to render pagination
            function renderPagination() {
                let totalPages = parseInt(page.totalPage);
                let currentPage = page.current;
                let pagination = $("#pagination");
                pagination.empty();

                // Render first page
                let firstPageItem = $("<li>")
                    .addClass("page-item")
                    .append($("<a>").addClass("page-link").text("首页"));
                if (currentPage == 1) {
                    firstPageItem.addClass("disabled");
                }
                pagination.append(firstPageItem);

                // Render previous page
                let previousPageItem = $("<li>")
                    .addClass("page-item")
                    .append($("<a>").addClass("page-link").text("上一页"));
                if (currentPage == 1) {
                    previousPageItem.addClass("disabled");
                }
                pagination.append(previousPageItem);

                // Render page numbers
                let visiblePages = Math.min(totalPages, 10);
                let startPage = Math.max(
                    1,
                    currentPage - Math.floor(visiblePages / 2)
                );
                let endPage = startPage + visiblePages - 1;
                if (totalPages <= 10) {
                    startPage = 1;
                    endPage = totalPages;
                }
                if (endPage > totalPages) {
                    endPage = totalPages;
                }
                for (let i = startPage; i <= endPage; i++) {
                    let pageItem = $("<li>")
                        .addClass("page-item")
                        .append($("<a>").addClass("page-link").text(i));
                    pagination.append(pageItem);
                }

                // Render next page
                let nextPageItem = $("<li>")
                    .addClass("page-item")
                    .append($("<a>").addClass("page-link").text("下一页"));
                if (currentPage >= totalPages) {
                    nextPageItem.addClass("disabled");
                }
                pagination.append(nextPageItem);

                // Render last page
                let lastPageItem = $("<li>")
                    .addClass("page-item")
                    .append($("<a>").addClass("page-link").text("末页"));
                if (currentPage >= totalPages) {
                    lastPageItem.addClass("disabled");
                }
                pagination.append(lastPageItem);

                // Highlight current page
                pagination
                    .find(".page-item")
                    .filter(function () {
                        return $(this).text() == currentPage;
                    })
                    .addClass("active");
            }

            $("#pagination").on("click", ".page-link", function () {
                let clickedPage = $(this).text();
                let currentPage = parseInt(page.current);
                let totalPage = parseInt(page.totalPage);
                if (clickedPage === "首页") {
                    currentPage = 1;
                } else if (clickedPage === "上一页") {
                    if (currentPage > 1) {
                        currentPage--;
                    }
                } else if (clickedPage === "下一页") {
                    if (currentPage < totalPage) {
                        currentPage++;
                    }
                } else if (clickedPage === "末页") {
                    currentPage = totalPage;
                } else {
                    currentPage = parseInt(clickedPage);
                }

                // Re-render list items and pagination
                getList(currentPage);
            });
            $("#updateWriteNameBtn").click(async function (e) {
                if(!$(".writeName-form")[0].checkValidity()){
                    $("#writeNameInfo").text("姓名不能为空");
                    $("#writeName").addClass("is-invalid");
                    return;
                }
                let res = await axios({
                    method: "put",
                    url: "/files/updateWriteName/" + updateId,
                    data: {
                        writeName: $("#writeName").val()
                    },
                });
                $("#updateWriteNameModal").modal("hide");
                getList(page.current);
               
            });
            $("#addBtn").click(async function () {
                if(!$(".add-form")[0].checkValidity()){
                    $("#fileNameInfo").text("验证码不能为空");
                    $("#fileName").addClass("is-invalid");
                    return;
                }
                let res = await axios({
                    method: "post",
                    url: "/files",
                    data: {
                        id: $("#fileName").val(),
                        type: "pdf",
                    },
                });
                if(res.data.status == 1){
                    
                    $("#addFileModal").modal("hide");
                    $("#qrcodeModal").modal("show");
                    generateQRCode(res.data.data.forwardUrl);
                    getList();
                }else{
                    
                    $("#fileNameInfo").text("此验证码对应的文件已存在，请重新输入");
                    $("#fileName").addClass("is-invalid");
                    return;
                }
            });
            $("#down-btn").click(function () {
                downQRCode("pdf.png");
            });
            $("#addFileModal").on("hidden.bs.modal",() => {
                $("#fileName").removeClass("is-invalid");
                $("#fileName").removeClass("is-valid");
                $(".add-form")[0].reset();
            });
            getList();
        </script>
    </body>
</html>
